/**
 *  2013-5-16   下午12:08:34
 *  Created By niexiaoqiang
 */

package com.xiaoqiang.object;

import java.awt.event.KeyEvent;

import javax.management.RuntimeErrorException;

import org.apache.log4j.Logger;

import com.xiaoqiang.main.MtwMain;

/**
 * TODO Add Class Description
 */
public class MtwObject {

	private String msg;
	private static Logger log = Logger.getLogger(MtwObject.class);

	public MtwObject(String msg) {
		this.msg = msg;
		log.debug("init MtwObject:" + msg);
	}

	public Object getObject() {
		String[] msg1 = msg.split("-");
		try {
			int keyCode = Integer.parseInt(msg1[0]);
			log.debug("spilit msg by \"-\":" + msg1[0] + "---------" + msg1[1]);
			if (msg1[1].equals("ACTION_DOWN")) {
				String properties = MtwMain.props.getProperty(String.valueOf(keyCode));
				if (null!=properties) {
					keyCode = Integer.parseInt(properties);
				}
				return new MtwKey(keyCode, 0);
			} else {
				String properties = MtwMain.props.getProperty(String.valueOf(keyCode));
				if (null!=properties) {
					keyCode = Integer.parseInt(properties);
				}
				return new MtwKey(keyCode, 1);
			}
		} catch (NumberFormatException e) {
			log.debug("convert to int failed and get MtwMouse object");
			if (msg1[0].equals("MouseMove")) {
				String XAndY = msg.substring(msg1[0].length());
				String S_X = XAndY.split(":")[1];
				Double D_X = Double.parseDouble(S_X.substring(0, S_X.length() - 2));
				log.debug("mousemove X :" + D_X);
				Double D_Y = Double.parseDouble(XAndY.split(":")[2]);
				return new MtwMouse(msg1[0], D_X, D_Y);
			} else if (msg1[0].equals("MouseWheel")) {
				String Y = msg.substring(msg1[0].length());
				Double D_Y = Double.parseDouble(Y.split(":")[1]);
				return new MtwMouse(msg1[0], D_Y);
			} else {
				if (msg1[0].equals("MouseLeft")) {
					int mousebutton = KeyEvent.BUTTON1_MASK;
					if (msg1[1].equals("ACTION_DOWN")) {
						mousebutton = Integer.parseInt(MtwMain.props.getProperty("leftbutton"));
						return new MtwMouse(msg1[0], mousebutton, 0);
					} else {
						mousebutton = Integer.parseInt(MtwMain.props.getProperty("leftbutton"));
						return new MtwMouse(msg1[0], mousebutton, 1);
					}
				} else if (msg1[0].equals("MouseRight")) {
					int mousebutton = KeyEvent.BUTTON3_MASK;
					if (msg1[1].equals("ACTION_DOWN")) {
						mousebutton = Integer.parseInt(MtwMain.props.getProperty("rightbutton"));
						return new MtwMouse(msg1[0], mousebutton, 0);
					} else {
						mousebutton = Integer.parseInt(MtwMain.props.getProperty("rightbutton"));
						return new MtwMouse(msg1[0], mousebutton, 1);
					}
				}
			}
		}
		log.debug("get object failed!!!");
		throw new RuntimeErrorException(null, "get object failed!!!");
	}
}
